const {
  wxParse
} = require('../../wxParse/wxParse')
const {
  STORAGE_CONSTANT
} = require('../../constant/index')
const {
  countReadings
} = require('../../api/article')
const {
  to,
  openLoading,
  closeLoading,
  showToast,
  getEventData
} = getApp()
Page({
  data: {
    articsDetail: null
  },
  onLoad() {
    this.getDetail()
  },

  getDetail() {
    const data = wx.getStorageSync(STORAGE_CONSTANT.articsRouteName);
    wx.removeStorageSync(STORAGE_CONSTANT.articsRouteName)
    data.wxParseContent = wxParse('introductionHtml', 'html', data.content, this, 5);
    this.setData({
      articsDetail: data
    })
    this.loadCountReadings(data)
  },

  async loadCountReadings(data) {
    openLoading()
    const [err] = await to(countReadings({
      articleId: data.articleId
    }))
    closeLoading()
    if (!err) {
      let readings = data.readings;
      readings++;
      this.setData({
        ['articsDetail.readings']: readings
      })
    }
  },

  wxParseTagATap(event) {
    console.log(event)
    const {
      src
    } = getEventData(event);

    this.openFile(src)
  },

  openFile(filePath) {
    openLoading('附件加载中');
    wx.downloadFile({
      url: filePath,
      success({
        statusCode,
        tempFilePath
      }) {
        if (statusCode === 200) {
          wx.openDocument({
            filePath: tempFilePath
          })
        }
      },

      fail() {
        showToast('暂不支持此格式文件')
      },
      complete() {
        hideLoading();
      }
    });
  }
})